/*
 * HttpParser.cpp
 *
 */

#include "HttpParser.h"
#include "HttpGet.h"
#include "HttpPost.h"

HttpParser::HttpParser() {
}

HttpParser::~HttpParser() {
}

HttpHeader* HttpParser::parseHeader(const std::string& line) {
	unsigned int nameEnd, valueBeg;
	unsigned int separator = line.find(HttpHeader::SEPARATOR);
	if (separator == std::string::npos || separator == 0)
		throw MessageException("Header error");
	nameEnd = line.find_first_of(HttpMessage::WHITES);
	nameEnd = (nameEnd > separator)? separator : nameEnd;
	valueBeg = line.find_first_not_of(HttpMessage::WHITES, separator + 1);
	std::string name = line.substr(0, nameEnd);
	std::string value = line.substr(valueBeg, line.length());
	return new HttpHeader(name, value);
}

HttpRequest* HttpParser::parseRequest(const std::string& line) {
	std::string method;
	std::string uri;
	std::string version;
	size_t firstSpace, lastSpace;
	firstSpace = line.find_first_of(HttpMessage::SP);
	lastSpace = line.find_last_of(HttpMessage::SP);
	method = line.substr(0, firstSpace);
	uri = line.substr(firstSpace + 1, lastSpace - 1 - firstSpace);
	version = line.substr(lastSpace + 1);
	HttpRequest* request = NULL;
	if (version == HttpHost::VERSION) {
		if (method == HttpRequest::GET)
			request = new HttpGet(uri);
		else if (method == HttpRequest::POST)
			request = new HttpPost(uri);
		else
			throw MessageException("Método no reconocido");
	}
	else
		throw MessageException("Versión de protocolo no aceptada");
	return request;
}
